package cn.tedu.sp02.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.sp01.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * @ClassName ItemController
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/6/22 14:02
 * @Version V1.0
 **/
@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    //获取订单的商品列表
    /*JsonResult 用来返回给客户端的数据
    * -code状态码 0
    * -msg 提示消息 null
    * -data 数据对象 List<Item>
    "{"code":0,"msg":"null","data"=[{},{}]}"
    * */
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        List<Item> items = itemService.getItems(orderId);
        JsonResult r = JsonResult.ok().data(items);
        
        //随机的延迟代码 90%概率会执行延迟代码
        if(Math.random()<0.9){
            int t = new Random().nextInt(5000);
            log.info("随机延迟: "+t);
            Thread.sleep(t);
        }
        return r;
    }

    //减少商品库存
    /*
     * @Requestbody
     接收客户端提交的参数
     完整德接收http协议体数据,再转成Java对象
     */

    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }

}
